package capacity

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/capacity"
	capacityReq "github.com/flipped-aurora/gin-vue-admin/server/model/capacity/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type CapacityService struct {
}

// CreateCapacity 创建capacity表记录
// Author [piexlmax](https://github.com/piexlmax)
func (capacitysService *CapacityService) CreateCapacity(capacitys *capacity.Capacity) (err error) {
	err = global.GVA_DB.Create(capacitys).Error
	return err
}

// DeleteCapacity 删除capacity表记录
// Author [piexlmax](https://github.com/piexlmax)
func (capacitysService *CapacityService) DeleteCapacity(capacitys capacity.Capacity) (err error) {
	err = global.GVA_DB.Delete(&capacitys).Error
	return err
}

// DeleteCapacityByIds 批量删除capacity表记录
// Author [piexlmax](https://github.com/piexlmax)
func (capacitysService *CapacityService) DeleteCapacityByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]capacity.Capacity{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateCapacity 更新capacity表记录
// Author [piexlmax](https://github.com/piexlmax)
func (capacitysService *CapacityService) UpdateCapacity(capacitys capacity.Capacity) (err error) {
	err = global.GVA_DB.Save(&capacitys).Error
	return err
}

// GetCapacity 根据id获取capacity表记录
// Author [piexlmax](https://github.com/piexlmax)
func (capacitysService *CapacityService) GetCapacity(id uint) (capacitys capacity.Capacity, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&capacitys).Error
	return
}

// GetCapacityInfoList 分页获取capacity表记录
// Author [piexlmax](https://github.com/piexlmax)
func (capacitysService *CapacityService) GetCapacityInfoList(info capacityReq.CapacitySearch) (list []capacity.Capacity, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&capacity.Capacity{})
	var capacityss []capacity.Capacity
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Name != "" {
		db = db.Where("name = ?", info.Name)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&capacityss).Error
	return capacityss, total, err
}
